import requests
import os
from tkinter import messagebox

getUrl = "http://121.41.112.199:3000/song/url"

def download(song):
        
    # 获取当前用户目录
    user_home = os.path.expanduser('~')
    #获取数据地址
    url = getUrl + "?id=" + str(song.get("id"))
    headers = {"Accept": "application/vnd.github.v3+json"}
    data = requests.get(url, headers=headers)
    response_dict = data.json()
    #获取数据
    try:
        file = requests.get(response_dict["data"][0]["url"])
        open(user_home+"/Music/"+song.get("name")+".mp3","wb").write(file.content)
        messagebox.showinfo("成功","音乐下载到："+user_home+"\\Music\\"+song.get("name")+".mp3")
    except requests.exceptions.MissingSchema as e:
        messagebox.showerror("错误","下载失败：未获取到地址")
    except:
        messagebox.showerror("错误","下载失败")